import http, { HttpRequest } from './request.js';
import { formatDate } from './utils.js';

class NoticeBoard {
    constructor() {
        this.noticeList = document.getElementById('noticeList');
        this.searchInput = document.getElementById('searchInput');
        this.currentPage = 1;
        this.loading = false;
        this.hasMore = true;
        this.searchBtn = document.querySelector('.search-btn');
        this.categorySelect = document.querySelector('.category-select');
        this.init();
    }

    async init() {
        await this.loadTags();
        this.loadPosts();
        this.bindEvents();
    }

    async loadTags() {
        try {
            const tags = await http.get('/tags', { type: 1 });
            this.categorySelect.innerHTML = `
                <option value="">All Categories</option>
                ${tags.map(tag => `
                    <option value="${tag.TagID}">${tag.Name}</option>
                `).join('')}
            `;
        } catch (error) {
            console.error('Failed to load tags:', error);
        }
    }

    async loadPosts(append = false) {
        if (this.loading) return;
        
        try {
            this.loading = true;
            
            if (!append) {
                this.currentPage = 1;
                this.noticeList.innerHTML = '';
            }

            const keyword = this.searchInput.value.trim();
            const tagId = this.categorySelect.value;
            const filter = document.querySelector('input[name="filter"]:checked')?.value;
            
            const params = {
                keyword,
                filter
            };

            if (tagId && !isNaN(parseInt(tagId))) {
                params.tagId = parseInt(tagId);
            }
            
            const response = await http.get(`/posts/page/${this.currentPage}`, params);

            if (!append) {
                this.noticeList.innerHTML = '';
            }

            this.hasMore = response.list?.length === response.limit;
            this.renderPosts(response.list || []);
        } catch (error) {
            if (error.code !== 403) {
                console.error('Failed to load posts:', error);
                alert('Failed to load posts: ' + error.message);
            }
        } finally {
            this.loading = false;
        }
    }

    renderPosts(posts) {
        const html = posts.map(post => `
            <div class="notice-item" data-id="${post.PostID}">
                <div class="notice-main">
                    ${post.Media ? (() => {
                        const mediaFiles = post.Media.split(',');
                        return `
                            <div class="notice-media">
                                ${mediaFiles[0].toLowerCase().endsWith('.mp4') ? `
                                    <video src="${mediaFiles[0]}" />
                                ` : `
                                    <img src="${mediaFiles[0]}" alt="Media content" />
                                `}
                                ${mediaFiles.length > 1 ? `
                                    <div class="media-count">+${mediaFiles.length - 1}</div>
                                ` : ''}
                            </div>
                        `;
                    })() : ''}
                    <div class="notice-content-wrapper">
                        <div class="notice-header">
                            <div class="notice-title-row">
                                ${(post.TagName || post.IsHot) ? `
                                    <div class="notice-tags">
                                        ${post.TagName ? `
                                            <span class="tag tag-category">${post.TagName}</span>
                                        ` : ''}
                                        ${post.IsHot ? `
                                            <span class="tag tag-hot">Popular</span>
                                        ` : ''}
                                    </div>
                                ` : ''}
                                <h3 class="notice-title">${http.escapeHtml(post.Title)}</h3>
                            </div>
                            <span class="notice-date">${post.CreateTime}</span>
                        </div>
                        <div class="notice-content">
                            ${http.formatContent(post.Content)}
                        </div>
                        <div class="notice-footer">
                            <div class="notice-author">
                                <img src="${post.AuthorAvatar || '../assets/images/default_photo.jpg'}" 
                                     alt="${post.AuthorName}" 
                                     class="author-avatar">
                                <span class="author-name">${post.AuthorName}</span>
                            </div>
                            <div class="notice-stats">
                                <span class="stat-item ${post.IsLiked ? 'active' : ''}" onclick="event.stopPropagation(); noticeBoard.handleLike(${post.PostID})">
                                    <i class="icon">👍</i>
                                    ${post.LikeCount}
                                </span>
                                <span class="stat-item">
                                    <i class="icon">💬</i>
                                    ${post.CommentCount}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `).join('');

        if (this.currentPage === 1) {
            this.noticeList.innerHTML = html;
        } else {
            this.noticeList.insertAdjacentHTML('beforeend', html);
        }
    }

    bindEvents() {
        // 点击帖子跳转到详情页
        this.noticeList.addEventListener('click', (e) => {
            const noticeItem = e.target.closest('.notice-item');
            if (noticeItem) {
                const postId = noticeItem.dataset.id;
                this.showPostDetail(postId);
            }
        });

        // 修改搜索事件，改为点击按钮触发
        this.searchBtn.addEventListener('click', () => {
            this.currentPage = 1;
            this.loadPosts();
        });

        // 添加回车键触发搜索
        this.searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.currentPage = 1;
                this.loadPosts();
            }
        });

        // 添加分类选择事件
        this.categorySelect.addEventListener('change', () => {
            this.currentPage = 1;
            this.loadPosts();
        });

        // 筛选切换
        const radioFilters = document.querySelectorAll('input[name="filter"]');
        radioFilters.forEach(radio => {
            radio.addEventListener('change', () => {
                this.currentPage = 1;
                this.loadPosts();
            });
        });

        // 滚动加载
        window.addEventListener('scroll', this.debounce(() => {
            if (this.loading || !this.hasMore) return;
            
            const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
            if (scrollHeight - scrollTop - clientHeight < 100) {
                this.currentPage++;
                this.loadPosts(true);
            }
        }, 100));
    }

    async handleLike(postId) {
        try {
            const response = await http.post(`/posts/${postId}/like`);
            // 重新加载当前页面的帖子
            this.loadPosts();
        } catch (error) {
            console.error('Failed to like post:', error);
            alert('Failed to like post: ' + error.message);
        }
    }

    showPostDetail(postId) {
        window.location.href = `./notice-detail.html?id=${postId}`;
    }

    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
}

// 创建全局实例
window.noticeBoard = new NoticeBoard(); 